﻿#region Usings
using System;
using BK.Entities;
using Lib.Data.CriteriaRoutine;
using Lib.Data.ORM;
using Lib.Data.ORM.Entity;
using Lib.Data.ORM.EntityManagement;
#endregion

namespace BK.BL
{
    [DataManager]
    public class Categories : BaseGeneralDataManager<CategoryEntity>
    {
        #region C'tors
        public Categories(BaseOrmDataBase ormDataBase) : base(ormDataBase)
        {
        }

        public IdentifierInt GetParentId(IdentifierInt parentId)
        {
            CategoryEntity[] categories = Select(parentId);
            return categories.Length == 0 ? new IdentifierInt() : categories[0].ParentId;
        }

        public CategoryEntity[] Select(IdentifierInt id)
        {
            Criteria criteria = new Criteria("Id.Value", Clause.Eq, id.Value);

            return BlContext.Instance.Categories.Load(criteria);
        }

    	public override IdentifierInt Insert(CategoryEntity entity)
    	{
    		DefineNestingLevel(entity);
    		return base.Insert(entity);
    	}

    	private void DefineNestingLevel(CategoryEntity entity)
    	{
    		if (entity.ParentId != null)
    		{
    			CategoryEntity parentCategoryEntity = BlContext.Instance.Categories.Load(entity.ParentId);
    			entity.NestingLevel = parentCategoryEntity.NestingLevel + 1;
    		}
    		entity.NestingLevel = 0;
    	}

    	public override bool Update(CategoryEntity entity)
    	{
			DefineNestingLevel(entity);
			return base.Update(entity);
    	}
    	#endregion
    }
}